﻿Option Explicit On
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
'file of project importing project/itself ?
'Imports EpubGen
'Imports System.Windows.Forms
'Imports D:\Users\admin\Desktop\epubcheck-0.9.2.jar



Public Class EpubCreator

    Private bookName As String
    Private imgCount
    Private fileImage(200) 'stores 200 files of pictures


    'Directories
    'the dirName directory is the main directory
    'it contains all files needed to build the epub format
    Private dirName As String
    Private dirOebps As String
    Private dirMetaInf As String
    Private dirImages As String



    'Files
    'mimetype
    Private mimeTypeContent As String
    Private fileMimetype As String

    'stylesheet.css
    Private fileStylesheet As String
    Private stylesheetContent As String

    'container.xml
    Private fileContainer As String


    'title.html
    Private fileTitle As String
    Private titleContent
    Private title As String 'the title of the book

    'content.opf
    Private fileContentOpf As String
    Private contentOpf

    'Table of content toc.ncx
    Private fileToc As String
    Private tocContent

    'content.html ; the book
    Private fileContentHtml As String
    Private contentHtml

    Private utf8 As Encoding = New UTF8Encoding



    Sub New(ByVal bookName As String, ByVal path As String)

        imgCount = 0
        Me.bookName = bookName

        'All Directories

        'root directory
        dirName = path
        'dirName = "c:\Users\mKane\desktop\tp_epub11_12"
        System.IO.Directory.CreateDirectory(dirName)

        dirOebps = dirName + "\OEBPS"
        System.IO.Directory.CreateDirectory(dirOebps)

        dirMetaInf = dirName + "\META-INF"
        System.IO.Directory.CreateDirectory(dirMetaInf)

        dirImages = dirOebps + "\images"
        System.IO.Directory.CreateDirectory(dirImages)

        'MimeType File
        mimeTypeContent = "application/epub+zip"

        Try
            fileMimetype = dirName + "\mimetype"
            WriteFileFunc(fileMimetype, mimeTypeContent)
        Catch ex As Exception
            MsgBox(ex.Message())
        End Try


        'stylesheet.css
        fileStylesheet = dirOebps + "\stylesheet.css"
        stylesheetContent = "body {" &
                                vbCrLf & "  font-family: sans-serif;" &
                                vbCrLf & "}" &
                                vbCrLf & "h1,h2,h3,h4 {" &
                                vbCrLf & "  font-family: serif;" &
                                vbCrLf & "  color: green;" &
                                vbCrLf & "}" &
                                vbCrLf & "img {" &
                                vbCrLf & "max-height: 100%;" &
                                vbCrLf & "max-width: 100%;" &
                                vbCrLf & "height: auto;" &
                                vbCrLf & "width: auto;" &
                                vbCrLf & "}" &
                                vbCrLf & "head{" &
                                vbCrLf & "position: absolute;" &
                                vbCrLf & "width:auto;" &
                                 vbCrLf & "min-width:100%;" &
                                 vbCrLf & "height:170px;" &
                                 vbCrLf & "background-color:rgb(216,228,255);" &
                                 vbCrLf & "left: 0px;" &
                                 vbCrLf & "top: 0px;" &
                                 vbCrLf & "margin:0px;" &
                                 vbCrLf & "text-align: left;" &
                                 vbCrLf & "white-space: nowrap;" &
                                 vbCrLf & "vertical-align: top;" &
                                 vbCrLf & "overflow:visible;" &
                                 vbCrLf & "z-index: 14;" &
                                vbCrLf & "}"
        WriteFileFunc(fileStylesheet, stylesheetContent)


        'container.xml
        fileContainer = dirMetaInf + "\container.xml"
        Dim containerXml = New XDocument()
        Dim containerContent =
            <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
                <rootfiles>
                    <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
                </rootfiles>
            </container>
        Dim containerComment As XComment =
           <!--
                   The value of full-path (in bold) is the only part of this file that will ever vary.
                  The directory path must be relative to the root of the EPUB file itself,
                 not relative to the META-INF directory.
                -->
        containerXml.Add(containerContent)
        '  containerXml.Add(containerComment)
        containerXml.Save(fileContainer)


        'title.html
        fileTitle = dirOebps + "\title.html"
        titleContent = New System.IO.StreamWriter(fileTitle)
        titleContent.writeLine("<?xml version=" & "'1.0'" & " encoding=" & "'utf-8'" & "?>")
        titleContent.writeLine("<html xmlns=" & """http://www.w3.org/1999/xhtml""" & ">")
        titleContent.write("    <head>" &
                            vbCrLf & "      <title>" + bookName + "     </title>" &
                            vbCrLf & "      <link type=" & """text/css""" & " rel=" & """stylesheet""" & " href=" & """stylesheet.css""" & " />" &
                            vbCrLf & "  </head>" & vbCrLf & "   <body>" &
                            vbCrLf & "      <div id=" & """head""" & ">" &
                            vbCrLf & "      <h4> Hello World: Team Projekt: EPUB</h4>")
        titleContent.Close()
        titleContent.Dispose()


        'content.html
        fileContentHtml = dirOebps + "\content.html"
        contentHtml = New System.IO.StreamWriter(fileContentHtml)
        contentHtml.WriteLine("<?xml version=" & "'1.0'" & " encoding=" & "'utf-8'" & "?>")
        contentHtml.WriteLine("<!DOCTYPE html PUBLIC " & """-//W3C//DTD XHTML 1.0 Transitional//EN""")
        contentHtml.WriteLine("                 " & """http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""" & ">")
        contentHtml.WriteLine("<html xmlns=" & """http://www.w3.org/1999/xhtml""" & ">")
        contentHtml.Write(
                            vbCrLf & "  <head>" &
                            vbCrLf & "      <meta http-equiv=" & """Content-Type""" & " content=" & """text/html; charset=UTF-8""" & "/>" &
                            vbCrLf & "      <link rel=" & """schema.DC""" & " href=" & """http://purl.org/dc/elements/1.1/""" & "/>" &
                            vbCrLf & "	    <title>" + bookName + "</title>" &
                            vbCrLf & "      <meta name=" & """DC.identifier""" & " content=" & """id_Hello_World""" & "/>" &
                            vbCrLf & "      <link type=" & """text/css""" & " rel=" & """stylesheet""" & " href=" & """stylesheet.css""" & "/>" &
                            vbCrLf & "  </head>" &
                            vbCrLf & "  <body>")
        contentHtml.Close()
        contentHtml.Dispose()


        'content.opf
        fileContentOpf = dirOebps + "\content.opf"
        contentOpf = New System.IO.StreamWriter(fileContentOpf)
        Dim str As String = "     <dc:title>" + bookName + "</dc:title>"
        contentOpf.WriteLine("<?xml version=" & "'1.0'" & " encoding=" & "'utf-8'" & "?>")
        contentOpf.WriteLine("<package xmlns=" & """http://www.idpf.org/2007/opf""" & vbCrLf &
            "                   xmlns:dc=" & """http://purl.org/dc/elements/1.1/""" & vbCrLf &
            "                   unique-identifier=" & """bookid""" & " version=" & """2.0""" & ">")
        contentOpf.WriteLine("  <metadata>")
        contentOpf.WriteLine(str)
        contentOpf.WriteLine("      <dc:creator>Mamadou Kane</dc:creator>")
        contentOpf.WriteLine("      <dc:identifier id=" & """bookid""" & ">urn:uuid:0cc33cbd-94e2-49c1-909a-72ae16bc2658</dc:identifier>")
        contentOpf.WriteLine("      <dc:language>en-US</dc:language>")
        contentOpf.WriteLine("      <meta name=" & """cover""" & " content=" & """cover-image""" & " />")
        contentOpf.WriteLine("  </metadata>")

        'Every file that goes into your digital book must be listed in the manifest.
        contentOpf.WriteLine("  <manifest>")
        contentOpf.WriteLine("      <item id=" & """ncx""" & " href=" & """toc.ncx""" & " media-type=" & """application/x-dtbncx+xml""" & "/>")
        contentOpf.WriteLine("      <item id=" & """cover""" & " href=" & """title.html""" & " media-type=" & """application/xhtml+xml""" & "/>")
        contentOpf.WriteLine("      <item id=" & """content""" & " href=" & """content.html""" & " media-type=" & """application/xhtml+xml""" & "/>")
        contentOpf.WriteLine("      <item id=" & """css""" & " href=" & """stylesheet.css""" & " media-type=" & """text/css""" & "/>")
        contentOpf.Close()
        contentOpf.Dispose()


        'toc.ncx
        fileToc = dirOebps + "\toc.ncx"
        tocContent = New System.IO.StreamWriter(fileToc)
        Dim str1 As String = "     <text>" + bookName + "</text>"
        tocContent.WriteLine("<?xml version=" & "'1.0'" & " encoding=" & "'utf-8'" & "?>")
        tocContent.WriteLine("<!DOCTYPE ncx PUBLIC " & """-//NISO//DTD ncx 2005-1//EN""")
        tocContent.WriteLine("           " & """http://www.daisy.org/z3986/2005/ncx-2005-1.dtd""" & ">")
        tocContent.WriteLine("<ncx  version=" & """2005-1""" & " xml:lang=" & """en""" & " xmlns=" & """http://www.daisy.org/z3986/2005/ncx/""" & ">")
        tocContent.Write(
                            vbCrLf & "  <head>" &
                            vbCrLf & "    <meta name=" & """dtb:uid""" & " content=" & """urn:uuid:0cc33cbd-94e2-49c1-909a-72ae16bc2658""" & "/>" &
                            vbCrLf & "    <meta name=" & """dtb:depth""" & " content=" & """1""" & "/>" &
                             vbCrLf & "   <meta name=" & """dtb:totalPageCount""" & " content=" & """0""" & "/>" &
                            vbCrLf & "    <meta name=" & """dtb:maxPageNumber""" & " content=" & """0""" & "/>" &
                            vbCrLf & "  </head>" & vbCrLf)
        tocContent.WriteLine("  <docTitle>" & vbCrLf & " " + str1 & vbCrLf & "  </docTitle>")
        tocContent.WriteLine(<navMap>
                                 <navPoint id="navpoint-1" playOrder="1">
                                     <navLabel>
                                         <text>Book cover</text>
                                     </navLabel>
                                     <content src="title.html"/>
                                 </navPoint>
                                 <navPoint id="navpoint-2" playOrder="2">
                                     <navLabel>
                                         <text>Contents</text>
                                     </navLabel>
                                     <content src="content.html"/>
                                 </navPoint>
                             </navMap>)
        tocContent.WriteLine("</ncx>")
        tocContent.Close()
        tocContent.Dispose()
    End Sub



    'Write a given text in a file
    'the content of the file will be overwritten
    'The file will be created if not existing
    Public Sub WriteFileFunc(ByVal filename As String, ByVal content As String)
        Dim textFileWriter As New IO.FileStream(filename, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.None)
        Dim fileWriter As New IO.StreamWriter(textFileWriter)
        fileWriter.Write(content)
        fileWriter.Close()
        textFileWriter.Close()
    End Sub



    'this function inserts an <img>-tag on the content.html file
    'the path of the file ist given relatively from the images-directory
    Public Sub AddImgContent(ByVal fileImage As String)
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        Dim str As String = "images/" & fileImage
        Dim altStr As String = "alt" & imgCount
        Dim str1 As String = "      <img src=" & """" & str & """" & " alt=" & """" & altStr & """" & " />"
        contentHtml.WriteLine()
        contentHtml.WriteLine(str1)
        contentHtml.close()
        contentHtml.Dispose()
    End Sub




    'here is the method to write text on the book
    Public Sub writeTexte(ByVal str As String)
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True)
        '       System.IO.File.AppendAllText(fileContentHtml, str)
        contentHtml.write(str)
        contentHtml.close()
        contentHtml.Dispose()
        '     System.IO.File.AppendAllText(fileContentHtml, str)
    End Sub

    ' method to write a text on the book with size, color, textstyle, bold, underline or cursive
    Public Sub writeText(ByVal textString As String, ByVal sizeValue As Integer, ByVal colorValue As String, ByVal textStyle As String, ByVal boldStyle As Boolean, ByVal cursiveStyle As Boolean, ByVal underlineStyle As Boolean)

        contentHtml = New System.IO.StreamWriter(fileContentHtml, True)

        Dim str As String

        str = ""

        If (boldStyle) Then
            str = str + "<b>"
        End If

        If (cursiveStyle) Then
            str = str + "<i>"
        End If

        If (underlineStyle) Then
            str = str + "<u>"
        End If

        'set to black, because it is epub (black and white screens)
        colorValue = "000000"

        str = str + "<font size=" + Chr(34) + sizeValue.ToString + " pt" + Chr(34) + "style = " + Chr(34) + "font-family: " + textStyle + Chr(34) + " color=" + Chr(34) + colorValue + Chr(34) + ">" + textString + "</font>"

        If (underlineStyle) Then
            str = str + "</u>"
        End If

        If (cursiveStyle) Then
            str = str + "</i>"
        End If

        If (boldStyle) Then
            str = str + "</b>"
        End If

        contentHtml.write(str)
        contentHtml.close()
        contentHtml.Dispose()

    End Sub



    Public Sub openDivision()
        Dim str As String = "   <div>"
        ' System.IO.File.AppendAllText(fileContentHtml, str)
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.writeLine(str)
        contentHtml.close()
        contentHtml.Dispose()
        'System.IO.File.AppendAllText(fileContentHtml, str)

    End Sub



    Public Sub closeDivision()
        Dim str As String = "   </div>"
        ' System.IO.File.AppendAllText(fileContentHtml, str)
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.writeLine(str)
        contentHtml.close()
        contentHtml.Dispose()
        'System.IO.File.AppendAllText(fileContentHtml, str)
    End Sub



    Public Sub OpenParagraph()
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.writeLine("<p>")
        contentHtml.close()
        contentHtml.Dispose()
    End Sub




    Public Sub CloseParagraph()
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.writeLine("</p>")
        contentHtml.close()
        contentHtml.Dispose()
    End Sub



    Public Sub insertTab()
        Dim str As String = "   "
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.write(str)
        contentHtml.close()
        contentHtml.Dispose()
    End Sub



    Public Sub writeSpace()
        Dim str As String = " "
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.write(str)
        contentHtml.close()
        contentHtml.Dispose()
    End Sub



    Public Sub writeBlankLine()
        Dim str As String = "</br>"
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.write(str)
        contentHtml.close()
        contentHtml.Dispose()
    End Sub



    'here to add the rest of the manifest
    'all files wich are part of the Epub are gone to be mentionned in the manifest
    Public Sub AddContentOpf(ByVal fileName As String, ByVal ending As String)
        contentOpf = New System.IO.StreamWriter(fileContentOpf, True, utf8)
        Dim str2 As String = "images/" & fileName & "." & ending
        Dim str3 As String = "image/" + ending
        Dim str4 As String = "      <item id=" & """" & fileName & """" & " href=" & """" & str2 & """" & " media-type=" & """" & str3 & """" & "/>"
        contentOpf.WriteLine(str4)
        contentOpf.close()
        contentOpf.Dispose()
    End Sub



    Public Sub FinishTitleContent(ByVal fileCover As String)
        titleContent = New System.IO.StreamWriter(fileTitle, True, utf8)
        Dim str As String = "images/" & fileCover
        Dim str1 As String = "      <img src=" & """" & str & """" & " alt=" & """Title page""" & " /></div>"
        titleContent.WriteLine()
        titleContent.WriteLine(str1)
        titleContent.Write(vbCrLf & "  </body>" & vbCrLf & "</html>")
        titleContent.close()
        titleContent.Dispose()
    End Sub




    Public Sub contentOpfFinish()
        contentOpf = New System.IO.StreamWriter(fileContentOpf, True, utf8)

        contentOpf.WriteLine("  </manifest>")

        'One way to think of the OPF spine is that it defines the order of the "pages" of the book.
        'The spine is read in document order, from top to bottom.
        contentOpf.WriteLine("  <spine toc=" & """ncx""" & ">")
        contentOpf.WriteLine("      <itemref idref=" & """cover""" & " linear=" & """no""" & "/>")
        contentOpf.WriteLine("      <itemref idref=" & """content""" & "/>")
        contentOpf.WriteLine("  </spine>")
        contentOpf.WriteLine("  <guide>")
        contentOpf.WriteLine("      <reference href=" & """title.html""" & " type=" & """cover""" & " title=" & """Cover""" & "/>")
        contentOpf.WriteLine("  </guide>")
        contentOpf.WriteLine("</package>")
        contentOpf.close()
        contentOpf.Dispose()
    End Sub



    'all bevor opened tags must be closed
    Public Sub finishBook()
        contentOpfFinish()
        Dim str As String = "   </body>" & vbCrLf & "</html>"
        contentHtml = New System.IO.StreamWriter(fileContentHtml, True, utf8)
        contentHtml.writeLine(str)
        contentHtml.close()
        contentHtml.Dispose()
    End Sub



    Public Sub ImageFileInsert(ByVal ImageData As Image, ByVal FilePath As String)
        Try
            'save an object as image from his given pathname
            ImageData.Save(FilePath)
        Catch ex As Exception
            ex.InnerException.ToString()
        End Try
    End Sub




    'from a given image path
    Public Sub getImage(ByVal pfad As String)
        Dim img As Image

        Try
            'here are the allowed formats
            System.IO.FileInfo.Equals(pfad, "jpg Files(*.jpg)* | *.jpg" +
                                      "png Files(*.png)* | *.png" +
                                      "jpeg Files(*.jpeg)* | *.jpeg" +
                                      "bmp Files(*.bmp)* | *.bmp" +
                                      "gif Files(*.gif)* | *.gif")
        Catch ex As Exception
            MsgBox(ex.Message().ToString())
        End Try

        'build an own path/pathname for the image
        'however it could be several images to put on the book
        Dim arr As Array = Split(pfad, ".")
        Dim pathImage As String = dirImages + "\PIC" & imgCount & "." + arr(1)

        Dim fileName As String = "PIC" & imgCount
        Dim fileImage As String = fileName & "." & arr(1)
        AddContentOpf(fileName, arr(1))

        'the first image corresponds the cover bild of the book
        If imgCount = 0 Then
            FinishTitleContent(fileImage)

            'all other images are part of the content of the book
        Else
            AddImgContent(fileImage)

        End If

        imgCount += 1

        Try
            'from a given path, it will be an image object created
            img = Image.FromFile(pfad)
            ImageFileInsert(img, pathImage)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub




    Public Sub zipEpub(ByVal epubName As String)
        Try
            'Dim zipPath As String
            'zipPath = CurDir() & "\zip.exe"
            'MsgBox(zipPath)

            Dim zipPathOnline As String = "http://www.panthes.de/teamprojekt/zip.exe"
            Dim targetFileName As String = dirName & "\zip.exe"
            Dim myWebClient As New System.Net.WebClient()
            myWebClient.DownloadFile(zipPathOnline, targetFileName)

            'FileCopy(zipPath, dirName & "\zip.exe")

            Dim file = New System.IO.StreamWriter(dirName & "\zip.bat")
            Dim cmd1 = "CHDIR " & dirName
            Dim cmd2 = "zip -0Xq " & epubName & ".epub mimetype"
            Dim cmd3 = "zip -Xr9Dq " & epubName & ".epub *"

            file.WriteLine(cmd1, 0, cmd1.Length)
            file.WriteLine(cmd2, 0, cmd2.Length)
            file.WriteLine(cmd3, 0, cmd3.Length)
            file.Close()
            file.Dispose()

            Shell(dirName & "\zip.bat")


            'Dim cmd1 = "chDir" & dirName
            ''MsgBox(CurDir)

            ''open a Windows dos shell editor
            'Shell("C:\Windows\system32\cmd.exe")
            'System.Windows.Forms.SendKeys.SendWait("chDir " & dirName)
            'System.Windows.Forms.SendKeys.Flush()
            'System.Windows.Forms.SendKeys.SendWait("{ENTER}")
            'System.Windows.Forms.SendKeys.Flush()

            ''the mimetype file ist not a part of the zip archiv
            'System.Windows.Forms.SendKeys.SendWait("zip -0Xq " + epubName + ".epub mimetype")
            'System.Windows.Forms.SendKeys.Flush()
            'System.Windows.Forms.SendKeys.SendWait("{ENTER}")
            'System.Windows.Forms.SendKeys.Flush()

            'System.Windows.Forms.SendKeys.SendWait("zip -Xr9Dq " + epubName + ".epub *")
            'System.Windows.Forms.SendKeys.Flush()
            'System.Windows.Forms.SendKeys.SendWait("{ENTER}")
            'System.Windows.Forms.SendKeys.Flush()

            'System.Windows.Forms.SendKeys.SendWait("exit")
            'System.Windows.Forms.SendKeys.Flush()
            'System.Windows.Forms.SendKeys.SendWait("{ENTER}")
            'System.Windows.Forms.SendKeys.Flush()

        Catch ex As Exception
            MsgBox(ex.StackTrace & ex.Message)
        End Try
    End Sub

End Class
